package com.yumis.service.modules.car.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yumis.service.common.enums.HttpState;
import com.yumis.service.common.exception.GlobalException;
import com.yumis.service.common.vo.Page;
import com.yumis.service.common.vo.Response;
import com.yumis.service.model.pojo.CarBrand;
import com.yumis.service.model.pojo.User;
import com.yumis.service.modules.car.mapper.CarBrandMapper;
import com.yumis.service.modules.car.service.CarBrandService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class CarBrandServiceImpl implements CarBrandService {
    @Resource
    private CarBrandMapper carBrandMapper;
    @Override
    public void addCarBrand(CarBrand carBrand) {
        carBrand.setCreateTime((int) (System.currentTimeMillis()/1000));
        carBrand.setUpdateTime((int) (System.currentTimeMillis()/1000));
        int i=carBrandMapper.insertSelective(carBrand);
        if (i !=1){
            throw new GlobalException(Response.buildResponse(HttpState.CREATED_FAILED));
        }

    }

    @Override
    public void updateCarBrand(CarBrand carBrand) {
        carBrand.setUpdateTime((int) (System.currentTimeMillis()/1000));
        int i=carBrandMapper.updateByPrimaryKeySelective(carBrand);
        if (i !=1){
            throw new GlobalException(Response.buildResponse(HttpState.UPDATE_ERROR));
        }
    }

    @Override
    public void deleteByIdCarBrand(Long id) {
        int i=carBrandMapper.deleteByPrimaryKey(id);
        if (i !=1){
            throw new GlobalException(Response.buildResponse(HttpState.DELETE_ERROR));
        }
    }

    @Override
    public void deleteCarBrand(Long[] ids) {
        for (Long id:ids){
            int i=carBrandMapper.deleteByPrimaryKey(id);
            if (i !=1){
                throw new GlobalException(Response.buildResponse(HttpState.DELETE_ERROR));
            }
        }
    }

    @Override
    public Page<CarBrand> queryCarBrand(Integer page, Integer rows) {
        PageHelper.startPage(page,rows);
        Example example = new Example(CarBrand.class);
        example.setOrderByClause("create_time asc");
        List<CarBrand> carBrandList=carBrandMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(carBrandList)){
            throw new GlobalException(Response.buildResponse(HttpState.DATA_NOT_FOUNT));
        }
        PageInfo<CarBrand> info = new PageInfo<>(carBrandList);
        return new Page<>(info.getTotal(),info.getPages(),carBrandList);
    }
}
